package com.key.puzzlemodel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.key.puzzlemodel.bean.HVPuzzleBean
import com.key.puzzlemodel.config.PuzzleConfig
import com.key.puzzlemodel.config.PuzzleConfig.START_PHOTO_List
import com.key.puzzlemodel.databinding.ActivityTransverseLongitudinalBinding
import com.key.puzzlemodel.databinding.RecycItemPuzzleBinding
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.puzzlephoto.PuzzlePhotoItemFragment
import com.key.puzzlemodel.transverselongitudinal.HVMVVMDialog
import com.key.puzzlemodel.transverselongitudinal.IPuzzleInterFace
import com.key.puzzlemodel.transverselongitudinal.TransverseLongitudinalMVVMViewModel
import com.key.puzzlemodel.transverselongitudinal.fragment.BackgroundFragment
import com.key.puzzlemodel.transverselongitudinal.fragment.BorderFragment
import com.key.puzzlemodel.transverselongitudinal.fragment.EditFragment
import com.key.puzzlemodel.transverselongitudinal.fragment.MenuFragment
import com.key.puzzlemodel.util.*
import kotlinx.coroutines.runBlocking
import java.util.*


/**
 *
 * @功能描述:     横纵向界面
 * @创建时间:     2022/1/4
 * @创建者:       阳
 * @修改时间:     2022/1/4
 * @修改者:       阳
 */
class TransverseLongitudinalActivity :
    BaseMVVMActivity<ActivityTransverseLongitudinalBinding, TransverseLongitudinalMVVMViewModel>(),
    IPuzzleInterFace, View.OnClickListener {


    override val layoutId: Int
        get() = R.layout.activity_transverse_longitudinal

    private val TAG = this.javaClass.simpleName


    lateinit var puzzleAdapter: PuzzleAdapter

    //菜单fragment
    var menuFragment: MenuFragment? = null

    //边框fragment
    var borderFragment: BorderFragment? = null

    //编辑fragment
    var editFragment: EditFragment? = null

    //背景fragment
    var backgroundFragment: BackgroundFragment? = null

    //UI顶部，导出按钮
    var txtSave: TextView? = null

    //设置列表的样式
    var itemDecoration: ItemDecoration? = null
    var recycHelper: ItemTouchHelper? = null


    override fun initView(savedInstanceState: Bundle?) {

        mVDB.clickListener = this
        var startList = intent.getStringArrayListExtra(START_PHOTO_List) as ArrayList<String>

        mVM.isVertical = intent.getBooleanExtra("isVertical", true)

        if (!startList.isNullOrEmpty()) {
            mVM.photoList.clear()

            if (mVM.isVertical) {
                findViewById<TextView>(R.id.txt_top_title).text =
                    getString(R.string.vertical_puzzle)
            } else {
                findViewById<TextView>(R.id.txt_top_title).text =
                    getString(R.string.horizontal_puzzle)

                //横屏时，宽高度互换
                var width = mVM.imgWidth
                mVM.imgWidth = mVM.imgHeight
                mVM.imgHeight = width
            }

            for (photoPath in startList) {
                mVM.photoList.add(HVPuzzleBean(photoPath, mVM.imgWidth, mVM.imgHeight))
            }
            //添加activity管理
            PuzzleAppManager.getInstance().addActivity(this)
            //初始化状态
            mVM.isUpdate.value = false
            initTopTitleView()
            updateRecyclerView(mVM.photoList, false)
            clickColorBackground(mVM.backgroundColor)
            initObserver()
            initPhoto()
            //根据传入的Bundle对象判断Activity是正常启动还是销毁重建
            if (savedInstanceState == null) {
                //设置第一个Fragment默认选中
                setFragment(mVM.MENUTYPE);
                //  Log.e(TAG, "当前线程为：" + Thread.currentThread());
            }

            puzzleAdapter.notifyDataSetChanged()
        } else {
            Toast.makeText(this, "列表数据为空", Toast.LENGTH_SHORT).show()
            this.finish()
        }
    }

    private fun initTopTitleView() {

        findViewById<ImageView>(R.id.image_return).setOnClickListener {
            onBackPressed()
        }

        //导出
        txtSave = findViewById<TextView>(R.id.txt_top_title_right)
        txtSave?.visibility = View.VISIBLE
        txtSave?.text = getString(R.string.str_puzzle_export)
        txtSave?.setOnClickListener {
            runBlocking {
                //导出的图片数据
                var saveList: ArrayList<Bitmap> = ArrayList()

                for (index in 0 until mVM.photoList.size) {
                    var left = 0
                    var right = 0
                    var top = 0
                    var bottom = 0
                    var widthOrHeight = 0
                    var direction = 0

                    if (mVM.isVertical) {
                        left = mVM.borderInsideNumber + mVM.borderOutsideNumber
                        right = mVM.borderInsideNumber + mVM.borderOutsideNumber

                        //第一个item 需要添加内侧和外侧边距属性
                        if (index == 0)
                            top = mVM.borderInsideNumber + mVM.borderOutsideNumber

                        //最后一个需要加上 外侧边距
                        bottom = if (index == mVM.photoList.size - 1) {
                            mVM.borderInsideNumber + mVM.borderOutsideNumber
                        } else {
                            //加上内侧边距
                            mVM.borderInsideNumber
                        }

                        widthOrHeight = BitmapUtil.dip2px(
                            this@TransverseLongitudinalActivity,
                            mVM.imgWidth
                        )
                        direction = 0
                    } else {
                        top = mVM.borderInsideNumber + mVM.borderOutsideNumber
                        bottom = mVM.borderInsideNumber + mVM.borderOutsideNumber

                        //第一个item 需要添加内侧和外侧边距属性
                        if (index == 0)
                            left = mVM.borderInsideNumber + mVM.borderOutsideNumber

                        //最后一个需要加上 外侧边距
                        right = if (index == mVM.photoList.size - 1) {
                            mVM.borderInsideNumber + mVM.borderOutsideNumber
                        } else {
                            //加上内侧边距
                            mVM.borderInsideNumber
                        }
                        widthOrHeight = BitmapUtil.dip2px(
                            this@TransverseLongitudinalActivity,
                            mVM.imgHeight
                        )
                        direction = 1
                    }

                    var bitmap = BitmapUtil.getDrawingBitmap(
                        left,
                        top,
                        right,
                        bottom,
                        BitmapUtil.dip2px(
                            this@TransverseLongitudinalActivity,
                            mVM.borderRoundNumber.toFloat()
                        ),
                        widthOrHeight,
                        direction,
                        BitmapFactory.decodeFile(
                            UriUtil.getPathForUri(
                                this@TransverseLongitudinalActivity,
                                Uri.parse(mVM.photoList[index].imagePath)
                            )
                        ),
                        mVM.backgroundColor,
                        mVM.photoList[index].rectf
                    )


                    val matrix = Matrix()
                    matrix.postRotate(mVM.photoList[index].rotation.toFloat())

                    val rotatedBitmap = Bitmap.createBitmap(
                        bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true
                    )


                    // Log.e("图片列表添加  ", " 合成次数：$index")
                    saveList.add(rotatedBitmap)
                }

                // Log.e("图片列表添加  ", " 添加完成")
                mVM.saveListObserver.value = saveList
            }
        }


        /**
         * 拾色器MotionEvent.ACTION_UP事件回调监听，手指离开时隐藏并设置颜色
         */
        mVDB.colorPicker.setOnActionUpListener {
            mVDB.colorPicker.visibility = View.GONE
            backgroundFragment?.setRecyclerViewBg(mVDB.colorPicker.color, -1)
        }
    }


    private fun initPhoto() {
        //获取Fragment管理器
        val mFragmentManager: FragmentManager = supportFragmentManager
        //开启事务
        val mTransaction: FragmentTransaction = mFragmentManager.beginTransaction()
        if (photoItemFragment == null) {
            photoItemFragment = PuzzlePhotoItemFragment()
            mTransaction.add(R.id.fragment_album_container, photoItemFragment!!, "photo_fragment")
        } else {
            mTransaction.show(photoItemFragment!!)
        }

        photoItemFragment!!.setOnPhotoSelectedListener {
//            if (photoAdapter.itemCount >= 20) {
//                Toast.makeText(requireActivity(), "最多可添加20张", Toast.LENGTH_SHORT).show()
//                return@setOnPhotoSelectedListener
//            }
            if (editFragment != null) {
                editFragment!!.updatePhotoList(it.toString())
            }
            closePhotoFragment()
        }
        //提交事务
        mTransaction.commitAllowingStateLoss()
    }


    /**
     * 事件监听
     */
    private fun initObserver() {
        mVM.isUpdate.observe(this) {
            if (it) {  //编辑状态
                //隐藏导出按钮
                txtSave?.visibility = View.GONE
            } else {   //非编辑状态
                //显示导出按钮
                txtSave?.visibility = View.VISIBLE
            }
        }


        mVM.saveListObserver.observe(this) { saveList ->
            var width = 0
            var height = 0

            for (index in 0 until saveList.size) {
                if (mVM.isVertical) {
                    height += saveList[index].height
                    width = saveList[index].width
                } else {
                    width += saveList[index].width
                    height = saveList[index].height
                }
            }
            // Log.e("宽高度：", "width= $width,height = $height ")

            var bitmap = BitmapUtil.bitmapListToBitmap(
                saveList,
                width,
                height,
                mVM.isVertical
            )

            if (null == bitmap) {
                Log.e(TAG, "bitmap为空")
                return@observe
            }
            BitmapUtil.savePuzzleBitmap(
                this@TransverseLongitudinalActivity,
                bitmap
            ) { state, path ->
                if (state) {
                    bitmap!!.recycle()
                    var intent = Intent()
                    intent.putExtra(PuzzleConfig.EDIT_RESULT, path)
                    setResult(Activity.RESULT_OK, intent)
                    finish()
                } else {
                    Toast.makeText(
                        this@TransverseLongitudinalActivity,
                        "导出失败，请重试",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }

    }


    /**
     * 修改recycler的布局
     */
    private fun updateRecyclerView(photoList: ArrayList<HVPuzzleBean>, isUpdate: Boolean) {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = if (mVM.isVertical) {
            LinearLayoutManager.VERTICAL
        } else {
            LinearLayoutManager.HORIZONTAL
        }
        mVDB.recyclerPhoto.layoutManager = layoutManager

//        var layoutParams: RelativeLayout.LayoutParams =
//            mVDB.recyclerPhoto.layoutParams as RelativeLayout.LayoutParams
//        layoutParams.leftMargin = mVM.borderOutsideNumber
//        layoutParams.rightMargin = mVM.borderOutsideNumber
//        layoutParams.topMargin = mVM.borderOutsideNumber
//        layoutParams.bottomMargin = mVM.borderOutsideNumber
//        mVDB.recyclerPhoto.layoutParams = layoutParams

        //设置一个选中的默认值
//        photoList[mVM.scrollIndex].isSelected = true

        puzzleAdapter = PuzzleAdapter(this, photoList, mVM.isVertical, isUpdate,
            object : PuzzleAdapter.ItemClick {
                override fun clickResult(position: Int, bean: HVPuzzleBean) {
                    //更新状态，仅在编辑状态下显示 背景
                    puzzleAdapter.updateItemState(position)
                    //标记位置
                    mVM.scrollIndex = position

                    if (editFragment != null && editFragment!!.isVisible) {
                        editFragment!!.updateData(mVM.photoList, mVM.scrollIndex)
                    }
                    if (!mVM.isUpdate.value!!) {
                        //弹出显示框
                        HVMVVMDialog(bean, object : HVMVVMDialog.DialogClick {
                            override fun clickDialogResult(puzzleBean: HVPuzzleBean) {
                                //更新view
                                puzzleAdapter.updateItem(position, puzzleBean)
                            }
                        }).show(supportFragmentManager, "del_choose_dialog")
                    }
                }

                override fun onItemMoveResult(fromPosition: Int, toPosition: Int) {
                    //更新状态，仅在编辑状态下显示 背景
                    puzzleAdapter.updateItemState(toPosition)
                    //标记位置
                    mVM.scrollIndex = toPosition

                    if (editFragment != null && editFragment!!.isVisible) {
                        editFragment!!.updateData(mVM.photoList, fromPosition, toPosition)
                    }
                }
            })
        mVDB.recyclerPhoto.adapter = puzzleAdapter

        //列表设置滑动，拖拽功能
        recycHelper =
            ItemTouchHelper(RecycItemTouchHelperCallback(puzzleAdapter!!, mVM.isVertical))
        recycHelper?.attachToRecyclerView(mVDB.recyclerPhoto)

        mVM.isUpdate.value = isUpdate
    }


    private fun setFragment(index: Int) {
        //获取Fragment管理器
        val mFragmentManager: FragmentManager = supportFragmentManager
        //开启事务
        val mTransaction: FragmentTransaction = mFragmentManager.beginTransaction()
        //隐藏所有Fragment
        hideFragments(mTransaction)
        when (index) {
            mVM.MENUTYPE ->  //显示对应Fragment
                if (menuFragment == null) {
                    menuFragment = MenuFragment()
                    mTransaction.add(R.id.relayout_menu, menuFragment!!, "menu_fragment")
                } else {
                    mTransaction.show(menuFragment!!)
                }
            mVM.BORDERTYPE -> {
                if (borderFragment == null) {
                    borderFragment = BorderFragment()
                    mTransaction.add(R.id.relayout_menu, borderFragment!!, "border_fragment")
                } else {
                    mTransaction.show(borderFragment!!)
                }
            }
            mVM.EDITTYPE -> {
                if (editFragment == null) {
                    editFragment = EditFragment()
                    mTransaction.add(R.id.relayout_menu, editFragment!!, "edit_fragment")
                } else {
                    mTransaction.show(editFragment!!)
                }

                //设置边距
                puzzleAdapter.updateLayoutPadding(5)

                mVM.isUpdate.value = true
                puzzleAdapter.updateItem(true)
                editFragment!!.updateData(mVM.photoList, mVM.scrollIndex)
            }
            mVM.BACKGROUNDTYPE -> {
                if (backgroundFragment == null) {
                    backgroundFragment = BackgroundFragment()
                    mTransaction.add(R.id.relayout_menu, backgroundFragment!!, "bg_fragment")
                } else {
                    mTransaction.show(backgroundFragment!!)
                }
            }
            else -> {}
        }
        //提交事务
        mTransaction.commitAllowingStateLoss()
    }

    //隐藏Fragment
    private fun hideFragments(transaction: FragmentTransaction) {
        if (menuFragment != null) {
            transaction.hide(menuFragment!!)
        }
        if (borderFragment != null) {
            transaction.hide(borderFragment!!)
        }
        if (editFragment != null) {
            transaction.hide(editFragment!!)
        }
        if (backgroundFragment != null) {
            transaction.hide(backgroundFragment!!)
        }
    }

    override fun clickStartFragment(type: Int) {
        mVM.isUpdate.value = false
        setFragment(type)

        if (type != mVM.MENUTYPE) {
            //隐藏导出按钮
            txtSave?.visibility = View.GONE
        } else {
            //显示导出按钮
            txtSave?.visibility = View.VISIBLE
        }
        closeClickPicker()
    }

    /**
     * 设置内边距
     */
    override fun clickUpdateBorderInside(tabBorderInside: Int) {
        //如果内侧边距变化，则更新view
        //Log.e("内边距：", "-- $tabBorderInside")
        if (itemDecoration != null) {
            mVDB.recyclerPhoto.removeItemDecoration(itemDecoration!!)
        }

        mVM.borderInsideNumber = tabBorderInside

        setItemDecoration()
    }

    override fun clickUpdateBorderOutside(tabBorderOutside: Int) {
        //外侧边距
//        val list = ArrayList<HVPuzzleBean>()
//        list.addAll(mVM.photoList)
//
//        for (index in 0 until mVM.photoList.size) {
//            mVM.photoList[index].imgHeight = mVM.imgHeight - tabBorderOutside
//            mVM.photoList[index].imgWidth = mVM.imgWidth - tabBorderOutside
//        }
//        mVM.tabBorderOutside = tabBorderOutside.toFloat()
//
//        puzzleAdapter.updateItem(mVM.photoList)

        // Log.e("外侧边距：", "-- $tabBorderOutside")
        if (itemDecoration != null) {
            mVDB.recyclerPhoto.removeItemDecoration(itemDecoration!!)
        }

        mVM.borderOutsideNumber = tabBorderOutside
        setItemDecoration()
    }


    /**
     * 重新设置列表边距
     */
    fun setItemDecoration() {
        if (null != itemDecoration)
            mVDB.recyclerPhoto.removeItemDecoration(itemDecoration!!)

        itemDecoration =
            ItemDecoration(
                mVM.borderInsideNumber,
                mVM.borderOutsideNumber,
                puzzleAdapter.itemCount,
                mVM.isVertical
            )
        mVDB.recyclerPhoto.addItemDecoration(itemDecoration!!)
    }


    /**
     * 设置圆角属性
     */
    override fun clickUpdateBorderRound(tabBorderRound: Int) {
        var round = BitmapUtil.dip2px(this, tabBorderRound.toFloat())
        // Log.e(TAG, "圆角属性： $round")
        for (index in 0 until mVM.photoList.size) {
            mVM.photoList[index].imgRound = round
        }
        mVM.borderRoundNumber = tabBorderRound
        puzzleAdapter.updateItem(mVM.photoList)
//        updateRecyclerView(mVM.photoList, false)
    }

    override fun showClickPicker() {
        //Log.e("背景", "showClickPicker")
        val bitmap =
            Bitmap.createBitmap(mVDB.flContent.width, mVDB.flContent.height, Bitmap.Config.RGB_565)
        val canvas = Canvas(bitmap)
        mVDB.flContent.draw(canvas)
        //弹出颜色选择器
        mVDB.colorPicker.setTempBitmap(bitmap)
        mVDB.colorPicker.setPickView(mVDB.flContent)
        mVDB.colorPicker.visibility = View.VISIBLE
    }

    override fun closeClickPicker() {
        if (mVDB.colorPicker.visibility == View.VISIBLE) {
            mVDB.colorPicker.visibility = View.GONE
        }
    }

    override fun clickColorBackground(bgColor: Int) {
        //Log.e("背景", "bgColor == $bgColor")
        mVDB.flContent.setBackgroundColor(bgColor)
        mVM.backgroundColor = bgColor
        closeClickPicker()
    }

    /**
     * 修改信息回调
     */
    override fun clickEditResult(list: ArrayList<HVPuzzleBean>?, scrollIndex: Int) {
        if (list != null) {
            //处理图片内外侧边距没有删减的问题
            for (index in 0 until list.size) {
                list[index].imgHeight = mVM.imgHeight - mVM.tabBorderOutside
                list[index].imgWidth = mVM.imgWidth - mVM.tabBorderOutside
                //清除缓存信息
                list[index].isSelected = false
            }
            mVM.photoList = ArrayList()
            mVM.photoList.addAll(list)

            if (null != editFragment) {
                editFragment!!.itemPhotoList = ArrayList()
            }
            mVM.scrollIndex = scrollIndex
        } else {
            //重置数据
            mVM.scrollIndex = -1

            if (null != editFragment) {
                editFragment!!.itemPhotoList = ArrayList()
            }

            for (index in 0 until mVM.photoList.size) {
                //清除缓存信息
                mVM.photoList[index].isSelected = false
            }
        }

        mVM.isUpdate.value = false
        setFragment(mVM.MENUTYPE)

        //设置边距
        puzzleAdapter.updateLayoutPadding(0)

        puzzleAdapter.updateItem(mVM.photoList)
        //滚动到指定位置
//        mVDB.recyclerPhoto.scrollToPosition(scrollIndex)


    }

    /**
     * 显示修改的信息，未导出
     */
    override fun clickEditItemShow(list: ArrayList<HVPuzzleBean>, scrollIndex: Int) {

        // Log.e(TAG, "显示修改的信息：mVM.borderRoundNumber== ${mVM.borderRoundNumber}")
        //处理图片内外侧边距没有删减的问题
        for (index in 0 until list.size) {
            list[index].imgHeight = mVM.imgHeight - mVM.tabBorderOutside
            list[index].imgWidth = mVM.imgWidth - mVM.tabBorderOutside
            list[index].isSelected = false
        }
        list[scrollIndex].isSelected = true

        puzzleAdapter.updateItem(list, true)
        //滚动到指定位置
        mVDB.recyclerPhoto.scrollToPosition(scrollIndex)
    }


    private var photoItemFragment: PuzzlePhotoItemFragment? = null


    override fun showPhotoFragment() {
        //显示相册
        mVDB.llAlbumBottom.visibility = View.VISIBLE
        //隐藏菜单
        mVDB.relayoutMenu.visibility = View.GONE
        //加载相册数据
        photoItemFragment!!.loadPhoto(java.util.ArrayList())
    }

    override fun closePhotoFragment() {
        //显示相册
        mVDB.llAlbumBottom.visibility = View.GONE
        //隐藏菜单
        mVDB.relayoutMenu.visibility = View.VISIBLE
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.img_puzzle_cancel -> {
                closePhotoFragment()
            }
        }
    }

    class ItemDecoration(
        var tabBorderInside: Int = 0,
        var tabBorderOutside: Int = 0,
        var itemCount: Int = 0,
        var isVertical: Boolean
    ) :
        RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
        ) {
            if (isVertical) {
                outRect.left = tabBorderInside + tabBorderOutside
                outRect.right = tabBorderInside + tabBorderOutside

                //第一个item 需要添加内侧和外侧边距属性
                if (parent.getChildAdapterPosition(view) == 0)
                    outRect.top = tabBorderInside + tabBorderOutside

                //最后一个需要加上 外侧边距
                if (parent.getChildAdapterPosition(view) == itemCount - 1) {
                    outRect.bottom = tabBorderInside + tabBorderOutside
                } else {
                    //加上内侧边距
                    outRect.bottom = tabBorderInside
                }
            } else {
//                outRect.right = space
//                outRect.top = space
//                outRect.bottom = space
//                if (parent.getChildAdapterPosition(view) == 0)
//                    outRect.left = space
                outRect.top = tabBorderInside + tabBorderOutside
                outRect.bottom = tabBorderInside + tabBorderOutside

                //第一个item 需要添加内侧和外侧边距属性
                if (parent.getChildAdapterPosition(view) == 0)
                    outRect.left = tabBorderInside + tabBorderOutside

                //最后一个需要加上 外侧边距
                if (parent.getChildAdapterPosition(view) == itemCount - 1) {
                    outRect.right = tabBorderInside + tabBorderOutside
                } else {
                    //加上内侧边距
                    outRect.right = tabBorderInside
                }
            }
        }

    }

    class PuzzleAdapter(
        val context: Context,
        private var photoList: ArrayList<HVPuzzleBean>,
        private var isVertical: Boolean,
        private var isUpdate: Boolean,
        private var itemListener: ItemClick? = null,
        var tabBorderInside: Int = 0,
        var tabBorderRound: Int = 0,
        var layoutPadding: Int = 0
    ) : RecyclerView.Adapter<PuzzleAdapter.ViewHolder>(), RecyclerMoveListener {

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): ViewHolder {
            return ViewHolder(
                DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.recyc_item_puzzle, parent, false
                )
            )
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {

            val bean = photoList[position]
            //Log.e("是否是编辑状态", "-- $isUpdate  ---- bean.imgRound==${bean.imagePath}")

//            Log.e("是否是编辑状态", "-- ${bean.rotation}  ---- bean.==${bean}")
            //设置宽高度
            holder.itemBinding.imgItemPhoto.layoutParams.width =
                BitmapUtil.dip2px(context, bean.imgWidth)

            holder.itemBinding.imgItemPhoto.layoutParams.height =
                BitmapUtil.dip2px(context, bean.imgHeight)

            //设置透明的背景颜色
            holder.itemBinding.relayoutBg.setBackgroundColor(
                ContextCompat.getColor(context, R.color.transparent)
            )

            holder.itemBinding.relayoutBg.setPadding(layoutPadding)

//            Log.e("修改信息回调", "item加载 isUpdate== ${isUpdate}")
            if (isUpdate) {
                if (isVertical) {
                    holder.itemBinding.imgItemSlidingVer.visibility = View.VISIBLE
                    holder.itemBinding.imgItemSlidingHor.visibility = View.GONE
                } else {
                    holder.itemBinding.imgItemSlidingVer.visibility = View.GONE
                    holder.itemBinding.imgItemSlidingHor.visibility = View.VISIBLE
                }
//                Log.e("修改信息回调", "item加载 == ${bean}")

                if (bean.isSelected) {
                    holder.itemBinding.relayoutBg.setBackgroundColor(
                        ContextCompat.getColor(context, R.color.color0084FF)
                    )
                }
            } else {
                holder.itemBinding.imgItemSlidingVer.visibility = View.GONE
                holder.itemBinding.imgItemSlidingHor.visibility = View.GONE
            }

//Translate           平移变换
//Rotate                旋转变换
//Scale                  缩放变换
//Skew                  错切变换
//            if (bean.rotation != 0) {
////                holder.itemBinding.imgItemPhoto.pivotX = bean.imgWidth / 2;
////                holder.itemBinding.imgItemPhoto.pivotY = bean.imgHeight / 2;//支点在图片中心
////                holder.itemBinding.imgItemPhoto.rotation = bean.rotation.toFloat()
//
////                holder.itemBinding.imgItemPhoto.animate().rotation(bean.rotation.toFloat())
//
//                val matrix = Matrix()
//                holder.itemBinding.imgItemPhoto.scaleType = ImageView.ScaleType.MATRIX
//                //旋转
////                matrix.postRotate(bean.rotation.toFloat(), pivotX.toFloat(), pivotY.toFloat())
//                matrix.setRotate(bean.rotation.toFloat(), bean.imgWidth / 2, bean.imgHeight / 2)
//
////                var scaleWidth = bean.imgWidth / holder.itemBinding.imgItemPhoto.measuredWidth
////                var scaleHeight = bean.imgHeight / holder.itemBinding.imgItemPhoto.measuredHeight
////                matrix.postScale(scaleWidth, scaleHeight)
//                holder.itemBinding.imgItemPhoto.imageMatrix = matrix
//            }

            //显示图片
//            Glide.with(context).load(bean.imagePath).into(holder.itemBinding.imgItemPhoto)
            Glide.with(context).asBitmap().load(bean.imagePath)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        var resizeDirection = if (isVertical) {
                            0
                        } else {
                            1
                        }
                        val matrix = Matrix()
                        matrix.postRotate(bean.rotation.toFloat())

                        val rotatedBitmap = Bitmap.createBitmap(
                            resource, 0, 0, resource.width, resource.height, matrix, true
                        )

                        holder.itemBinding.imgItemPhoto.setViewData(
                            rotatedBitmap,
                            bean,
                            resizeDirection
                        )
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {}
                })

            holder.itemBinding.imgItemPhoto.setOnClickListener {
                itemListener?.clickResult(position, bean)
            }


        }

        override fun getItemCount(): Int {
            return photoList.size
        }

        inner class ViewHolder(val itemBinding: RecycItemPuzzleBinding) :
            RecyclerView.ViewHolder(itemBinding.root) {
        }


        interface ItemClick {
            fun clickResult(position: Int, bean: HVPuzzleBean)

            fun onItemMoveResult(fromPosition: Int, toPosition: Int)
        }

        fun updateItem(position: Int, bean: HVPuzzleBean) {
            photoList[position] = bean
            notifyItemChanged(position)
        }

        fun updateItem(updateState: Boolean) {
            isUpdate = updateState
            notifyDataSetChanged()
        }

        fun updateItem(list: ArrayList<HVPuzzleBean>) {
            updateItem(list, false)
        }

        fun updateLayoutPadding(padding: Int) {
            layoutPadding = padding
        }


        fun updateItem(list: ArrayList<HVPuzzleBean>, updateState: Boolean) {
            photoList = ArrayList()
            photoList.addAll(list)
            isUpdate = updateState
            notifyDataSetChanged()
        }

        fun updateItem(
            borderInside: Int,
            borderRound: Int
        ) {
            tabBorderInside = borderInside
            tabBorderRound = borderRound
            this.notifyDataSetChanged()
        }


        /**
         * 修改选中的状态（仅在编辑状态下使用）
         *  @param position  选中的下标
         */
        fun updateItemState(position: Int) {
            for (index in 0 until photoList.size) {
                photoList[index].isSelected = false
            }
            photoList[position].isSelected = true
            notifyDataSetChanged()
        }

        /**
         * 手势操作时间
         */
        override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
            // Log.e("手势操作时间", "fromPosition == $fromPosition  -- toPosition==$toPosition")
            Collections.swap(photoList, fromPosition, toPosition)
            notifyItemMoved(fromPosition, toPosition)
            if (null != itemListener) {
                itemListener!!.onItemMoveResult(fromPosition, toPosition)
            }
            return true
        }

        override fun onItemRemove(position: Int): Boolean {
            try {
                photoList.removeAt(position)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            notifyDataSetChanged()
            return true
        }

        override fun getItemViewType(position: Int): Int {
            return position
        }


        override fun isLongPressDragEnabled(): Boolean {
            //是否允许长按拖拽
            return isUpdate
        }

        override fun isItemViewSwipeEnabled(): Boolean {
            return false
        }

        private var DRAG = false

        override fun clearView(viewHolder: RecyclerView.ViewHolder?, recyclerView: RecyclerView?) {
            if (DRAG) {
                //拖拽 刷新
                notifyDataSetChanged()
            }
            if (viewHolder != null) {
                (viewHolder as PuzzleAdapter.ViewHolder).itemBinding.flDrag.visibility = View.GONE
            }
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            //如果不是编辑状态，则不滑动列表
            if (!isUpdate) {
                return
            }
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                DRAG = true
            }
            if (viewHolder != null) {
                VibratorUtil.onVibrator(viewHolder.itemView.context)
                (viewHolder as PuzzleAdapter.ViewHolder).itemBinding.flDrag.visibility =
                    View.VISIBLE
            }
        }
    }
}

